import React, { useContext, useEffect, useState } from 'react';
import { Button, InputNumber } from 'antd';
import { ConfigContext } from '../../configProvider';
import './index.less';
import classNames from 'classnames';

interface MineSweepingProps {
  level: number;
  bomb: number;
}

const MineSweeping: React.FC<MineSweepingProps> = ({ level, bomb }) => {
  const { prefix } = useContext(ConfigContext);
  const pf = prefix + '-mine-sweeping';

  if (!level) {
    level = 10;
  }
  if (!bomb) {
    bomb = 10;
  }
  const [levels, setLevels] = useState<number>(level);
  const [bombs, setBombs] = useState<number>(bomb);
  const [board, setBoard] = useState<number[][]>([[]]);
  const [live, setLive] = useState<boolean>(true);
  const [tips, setTips] = useState<string>('');
  const [leftCells, setLeftCells] = useState<number>(0);

  const initGame = () => {
    let tempBoard: number[] = [];
    for (let i = 0; i < levels * levels; i++) {
      if (i < bombs) {
        tempBoard.push(-1);
      } else {
        tempBoard.push(0);
      }
    }
    for (let i = 0; i < bombs; i++) {
      let target = Math.floor(Math.random() * levels * levels);
      let tempVal = tempBoard[target];
      tempBoard[target] = tempBoard[i];
      tempBoard[i] = tempVal;
    }
    let newBoard: number[][] = [];
    for (let i = 0; i < levels; i++) {
      newBoard.push(tempBoard.slice(i * levels, i * levels + levels));
    }
    for (let i = 0; i < levels; i++) {
      for (let j = 0; j < levels; j++) {
        if (newBoard[i][j] === -1) {
          for (let i0 = -1; i0 <= 1; i0++) {
            for (let j0 = -1; j0 <= 1; j0++) {
              if (
                newBoard[i + i0] !== undefined &&
                newBoard[i + i0][j + j0] != undefined &&
                newBoard[i + i0][j + j0] >= 0 &&
                (j0 !== 0 || i0 !== 0)
              ) {
                newBoard[i + i0][j + j0]++;
              }
            }
          }
        }
      }
    }
    setBoard(newBoard);
    setLive(true);
    setTips('');
    setLeftCells(levels * levels);
  };

  useEffect(() => {
    for (let x = 0; x < levels; x++) {
      for (let y = 0; y < levels; y++) {
        let cell = document.getElementById(`${pf}-${x}-${y}`);
        if (cell) {
          cell.style.opacity = live ? '0' : '1';
        }
      }
    }
  }, [board, live]);
  useEffect(() => {
    console.log('leftCells', leftCells);
    if (leftCells === bombs) {
      setTips('You Win!');
      for (let x = 0; x < levels; x++) {
        for (let y = 0; y < levels; y++) {
          let cell = document.getElementById(`${pf}-${x}-${y}`);
          if (cell && cell.style.opacity !== '1') {
            cell.style.opacity = '1';
          }
        }
      }
    }
  }, [leftCells]);

  const swap = (indexX: number, indexY: number) => {
    let cell = document.getElementById(`${pf}-${indexX}-${indexY}`);
    if (cell && cell.style.opacity !== '1') {
      let cnt = 0;
      if (live && board[indexX][indexY] === -1) {
        setLive(false);
        setTips('You Died!');
      } else {
        cell.style.opacity = '1';
        cnt++;
      }
      if (board[indexX][indexY] === 0) {
        cnt += autoSwap(indexX, indexY);
      }
      setLeftCells(leftCells - cnt);
    }
  };

  const autoSwap = (indexX: number, indexY: number) => {
    console.log('auto swap', indexX + ' ' + indexY);
    let cnt = 0;
    for (let x = -1; x <= 1; x++) {
      for (let y = -1; y <= 1; y++) {
        if (indexX + x >= 0 && indexX + x < levels && indexY + y >= 0 && indexY + y < levels) {
          let cell = document.getElementById(`${pf}-${indexX + x}-${indexY + y}`);
          if (cell && cell.style.opacity !== '1') {
            cell.style.opacity = '1';
            cnt++;
            if (board[indexX + x][indexY + y] === 0) {
              cnt += autoSwap(indexX + x, indexY + y);
            }
          }
        }
      }
    }
    return cnt;
  };

  const GameBoard = (
    <div id={`${pf}-board`} className={`${pf}-board`}>
      {board.map((value, index) => {
        let preIndex = index;
        return (
          <div id={`${pf}-${preIndex}`} className={`${pf}-row`}>
            {value.map((value, index) => {
              // return <div id={`${pf}-${preIndex}-${index}`} className={`${pf}-cell ${pf}-cell-${value}`} onClick={() => { swap(preIndex, index) }} ></div>
              return (
                <div
                  id={`${pf}-${preIndex}-${index}`}
                  className={`${pf}-cell ${pf}-cell-${value} ${
                    value === -1 && live ? pf + '-cell-win' : ''
                  }`}
                  onClick={() => {
                    swap(preIndex, index);
                  }}
                >
                  {' '}
                  {value === -1 || value === 0 ? '' : value}
                </div>
              );
            })}
          </div>
        );
      })}
    </div>
  );

  return (
    <div className={`${pf}`}>
      <div className={`${pf}-bar`}>
        <Button onClick={initGame}>New Game</Button>
        <div>{tips}</div>
        <InputNumber
          prefix="Level"
          min={3}
          max={30}
          value={levels}
          onChange={(value) => setLevels(value ? value : 10)}
        />
        <InputNumber
          prefix="Bomb"
          min={1}
          max={Math.min(levels * levels - 1, 99)}
          value={bombs}
          onChange={(value) => setBombs(value ? value : 10)}
        />
      </div>
      {GameBoard}
    </div>
  );
};

export default MineSweeping;
